<?php

namespace plugin\voice\app\controller;

use plugin\ai\app\model\AiUser as AiUserPlus;
use plugin\gpt\app\model\AiUser as AiUserNormal;
use plugin\voice\app\service\ChatGpt;
use plugin\voice\app\service\Common;
use plugin\voice\app\service\Setting;
use plugin\ai\app\service\User as UserPlus;
use plugin\gpt\app\service\User as UserNormal;
use plugin\user\api\Limit;
use support\Db;
use support\exception\BusinessException;
use support\Response;
use Throwable;

class Base
{

    /**
     * 尝试减少余额
     * @param $modelType
     * @param $isVip
     * @return string|null
     * @throws BusinessException
     */
    public static function tryReduceBalance($modelType, &$isVip)
    {
        if (!Common::modelEnabled($modelType)) {
            return "系统未开启 $modelType 功能";
        }
        $request = request();
        $session = $request->session();
        $loginUser = $session->get('user');
        $loginUserId = $loginUser['uid'] ?? $loginUser['id'] ?? null;
        $expired = false;
        $gpt             = config('plugin.gpt.app');
        if($gpt){
            $isVip = $loginUserId && UserNormal::isVip($loginUserId, $expired);
        }else{
            $isVip = $loginUserId && UserPlus::isVip($loginUserId, $expired);
        }
        
        if ($expired) {
            return "会员已经过期，[请续费](/app/ai/user/vip)";
        }

        if (!$loginUserId && Setting::getSetting('need_login')) {
            return "[请登录](/app/ai/user/login)";
        }
        // 尝试从余额中扣除
        if($gpt){
            if ($loginUserId && UserNormal::reduceBalance($loginUserId, $modelType)) {
                return null;
            }
        }else{
            if ($loginUserId && UserPlus::reduceBalance($loginUserId, $modelType)) {
                return null;
            }
        }
       

        // 余额不足则使用每日赠送余额
        $freeCountPerDay = Common::getDayFreeCount($modelType);
        try {
            if (!$freeCountPerDay) {
                throw new BusinessException('余额不足');
            }
            Limit::perDay($session->getId() . "-ai-$modelType-", $freeCountPerDay);
            $ip = request()->getRealIp();
            // 非内网ip时
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                Limit::perDay("$ip-ai-$modelType-", $freeCountPerDay);
            }
            // 消息加1
            if($gpt){
                if ($loginUserId) {
                    AiUserNormal::where('user_id', $loginUserId)->update([
                        'message_count' => Db::raw('message_count + 1'),
                    ]);
                }
            }else{
                if ($loginUserId) {
                    AiUserPlus::where('user_id', $loginUserId)->update([
                        'message_count' => Db::raw('message_count + 1'),
                    ]);
                }
            }
           
        // 赠送余额不足则给出提示
        } catch (Throwable $e) {
            if($gpt){
                if ($isVip) {
                    return  "您的账户{$modelType}额度不足，如需继续使用请 [续费](/app/gpt/user/vip?redirect=".urlencode('/app/gpt').")";
                }
                return "您今天{$modelType}消息已经达到上限，如需继续使用请 [升级会员](/app/gpt/user/vip?redirect=".urlencode('/app/gpt').")";
            }else{
                if ($isVip) {
                    return  "您的账户{$modelType}额度不足，如需继续使用请 [续费](/app/ai/user/vip?redirect=".urlencode('/app/ai').")";
                }
                return "您今天{$modelType}消息已经达到上限，如需继续使用请 [升级会员](/app/ai/user/vip?redirect=".urlencode('/app/ai').")";
            }
            
        }

        return null;
    }

    /**
     * @param $code
     * @param string $msg
     * @param mixed $data
     * @return Response
     */
    protected function json($code, string $msg = 'ok', $data = []): Response
    {
        return json(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }

}
